package com.skwen.delivery.superdelivery;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.skwen.delivery.superdelivery.baseinterface.MyOnClickListener;
import com.skwen.delivery.superdelivery.baseinterface.RegisterOnClickListener;
import com.skwen.delivery.superdelivery.login.bean.User;
import com.skwen.delivery.superdelivery.view.LoadingDialog;
import com.tencent.mapsdk.raster.model.LatLng;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by skwen on 2017/8/10.
 * SuperDelivery
 */

public class BaseActivity extends AppCompatActivity {


    protected AlertView mAlertView;//对话框
    protected Context mContext;
    protected Handler mHandler = new Handler();
    private LoadingDialog mLoadingDialog;//加载
    private AlertDialog.Builder dialog;
    private AlertDialog alertDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;

    }

    /**
     * 简单确认对话框
     *
     * @param title
     * @param content
     * @param myOnClickListener
     */

    protected void showConfirmSimpleDialog(String title, String content, MyOnClickListener myOnClickListener) {
        mAlertView = new AlertView(title, content, null, new String[]{"确定"}, null, this,
                AlertView.Style.Alert, (o, position) -> {
            myOnClickListener.myOnClickListener(position);
        });
        mAlertView.show();
    }

    /**
     * 简单确认对话框带取消
     *
     * @param title
     * @param content
     * @param myOnClickListener
     */

    protected void showConfirmDialog(String title, String content, MyOnClickListener myOnClickListener) {
        mAlertView = new AlertView(title, content, null, new String[]{"取消", "确定"}, null, this,
                AlertView.Style.Alert, (o, position) -> {
            switch (position) {
                case 0:
                    mAlertView.dismiss();
                    break;
                case 1:
                    myOnClickListener.myOnClickListener(position);
                    mAlertView.dismiss();
                    break;
            }
        });
        mAlertView.show();
    }

    /**
     * @param textView
     * @param title
     * @param items    // 单选提示框
     */

    public void showSingleAlertDialog(TextView textView, String title, String[] items) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(title);
        alertBuilder.setItems(items, (arg0, index) -> {
            textView.setText(items[index]);
            alertDialog.dismiss();
        });
        alertDialog = alertBuilder.create();
        alertDialog.show();
    }

    protected void showEditDialog(String title, RegisterOnClickListener myOnClickListener) {
        dialog = new AlertDialog.Builder(mContext);
        View view = getLayoutInflater().inflate(R.layout.layout_edit_dialog, null);
//        LayoutEditDialogBinding layoutEditDialogBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.layout_edit_dialog, null, false);
        AppCompatTextView titleText = (AppCompatTextView) view.findViewById(R.id.dialog_title);
        TextInputEditText editPhone = (TextInputEditText) view.findViewById(R.id.dialog_edit);
        TextInputEditText editCode = (TextInputEditText) view.findViewById(R.id.dialog_edit_code);
        TextInputEditText editPassWord = (TextInputEditText) view.findViewById(R.id.dialog_edit_password);
        LinearLayout dialog_layout_cancle_confirm = (LinearLayout) view.findViewById(R.id.dialog_layout_cancle_confirm);
        LinearLayout dialog_layout_next = (LinearLayout) view.findViewById(R.id.dialog_layout_next);
        TextView dialog_cancle = (TextView) view.findViewById(R.id.dialog_cancle);
        TextView dialog_confirm = (TextView) view.findViewById(R.id.dialog_confirm);
        TextView dialog_next = (TextView) view.findViewById(R.id.dialog_next);
        if (!TextUtils.isEmpty(title)) {
            titleText.setText(title);
        }
        dialog_next.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(editPhone.getText())
//                    && isMobileNO(editPhone.getText().toString())
                    ) {
                myOnClickListener.myOnClickListener(0, editPhone.getText().toString());//下一步
                dialog_layout_next.setVisibility(View.GONE);
                dialog_layout_cancle_confirm.setVisibility(View.VISIBLE);
                editCode.setVisibility(View.VISIBLE);
                editPassWord.setVisibility(View.VISIBLE);
            } else {
                showToast(v, getResources().getString(R.string.dialog_input_edit));
                dialog_layout_next.setVisibility(View.VISIBLE);
                dialog_layout_cancle_confirm.setVisibility(View.GONE);
                editCode.setVisibility(View.GONE);
                editPassWord.setVisibility(View.GONE);
            }
        });

        dialog_cancle.setOnClickListener(v -> {
            myOnClickListener.myOnClickListener(1, null);//取消
            alertDialog.dismiss();
        });

        dialog_confirm.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(editPhone.getText()) && !TextUtils.isEmpty(editCode.getText()) && !TextUtils.isEmpty(editPassWord.getText())) {
                User user = new User();
                user.setUserName(editPhone.getText().toString());
                user.setUserPhone(editPhone.getText().toString());
                user.setUserAccount(editPhone.getText().toString());
                user.setUserPsd(editPassWord.getText().toString());
                user.setUserSex("未设置");
                myOnClickListener.myOnClickListener(2, user);//確認
                alertDialog.dismiss();
            } else {
                showToast(v, "请填写完整信息");
            }
        });
        dialog.setView(view);
        dialog.setCancelable(false);
        dialog.setOnKeyListener((DialogInterface dialog, int keyCode, KeyEvent event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                alertDialog.dismiss();
                return true;
            } else
                return false;
        });
        alertDialog = dialog.show();
    }


    /**
     * 加载（带加载字，不可手动取消）
     */

    protected void showLoading() {
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(mContext)
                .setMessage("加载中...")
                .setCancelable(false);
        mLoadingDialog = builder1.create();
        mLoadingDialog.show();
    }

    /**
     * 加载（带加载字，可手动取消）
     */

    protected void showHandLoading() {
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(mContext)
                .setMessage("加载中...")
                .setCancelable(true);
        mLoadingDialog = builder1.create();
        mLoadingDialog.show();
    }

    /**
     * 加载（不带加载字，不可手动取消）
     */

    protected void showNoMsgLoading() {
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(mContext)
                .setShowMessage(false)
                .setCancelable(false);
        mLoadingDialog = builder1.create();
        mLoadingDialog.show();
    }

    /**
     * 加载（不带加载字，可手动取消）
     */

    protected void showNoMsgHandLoading() {
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(mContext)
                .setShowMessage(false)
                .setCancelable(true);
        mLoadingDialog = builder1.create();
        mLoadingDialog.show();
    }

    /**
     * 停止加载
     */
    protected void stopLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }


    protected void showToast(View view, String msg) {
        Snackbar.make(view, msg, Snackbar.LENGTH_SHORT)
                .setAction("Action", null).show();
    }


    /**
     * @param mobiles
     * @return 判断是否手机号
     */

    protected boolean isMobileNO(String mobiles) {


        Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(18[0,5-9])|(17[0-9]))\\d{8}$");


        Matcher m = p.matcher(mobiles);


        return m.matches();


    }


    /**
     * 获取String
     */
    protected String getIfNullText(CharSequence charSequence) {
        if (!TextUtils.isEmpty(charSequence)) {
            return charSequence.toString();
        } else return "";
    }


    /**
     * 计算两点之间距离
     *
     * @param start
     * @param end
     * @return 米
     */
    public double getDistance(LatLng start, LatLng end) {
        double lat1 = (Math.PI / 180) * start.getLatitude();
        double lat2 = (Math.PI / 180) * end.getLatitude();

        double lon1 = (Math.PI / 180) * start.getLongitude();
        double lon2 = (Math.PI / 180) * end.getLongitude();

//      double Lat1r = (Math.PI/180)*(gp1.getLatitudeE6()/1E6);
//      double Lat2r = (Math.PI/180)*(gp2.getLatitudeE6()/1E6);
//      double Lon1r = (Math.PI/180)*(gp1.getLongitudeE6()/1E6);
//      double Lon2r = (Math.PI/180)*(gp2.getLongitudeE6()/1E6);

        //地球半径
        double R = 6371;

        //两点间距离 km，如果想要米的话，结果*1000就可以了
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;

        return d * 1000;
    }
}
